package com.distribute.application.manage;

import com.distribute.framework.core.web.helper.Utils;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.distribute.framework.core.util.IbatisMap;

import com.distribute.framework.core.web.helper.WebHelper.DateExp;
import com.distribute.framework.core.lang.*;


public class ActionHelper {
	
	
	/**
	 * 处理页面的视图数据，比如显示哪些列，自定义显示列等
	 */
	public static void doPageViewFields(Class modelClass){
		String className = modelClass.getSimpleName();//类名
		String strFields = Utils.getString("fields");
		if(strFields!=null){
			Utils.setCookie(Utils.getServletRequest().getServletPath().replaceAll("/[^\\/]+$", ""),className+"Fields",strFields.replace(",", "|"));
		}else{
			strFields = Utils.getCookieValue(""+className+"Fields");
			if(strFields!=null){
				Utils.setRequest("fields", strFields.replace("|", ","));
			}
		}
	}
	
	
	
	/**
	 * 根据对象转为数据库需要的set条件
	 * @param csMemberInfo
	 * @return
	 */
	public static Map getSetValuesFromModel(Object object) {
		Map values=new HashMap();
		Field[] fields = object.getClass().getDeclaredFields();
		for(Field field:fields){
			column column = field.getAnnotation(column.class);
			if(column==null)continue;
			try {
				field.setAccessible(true);
				Object value = field.get(object);
				if(value!=null)
					values.put(field.getName(),value);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return values;
	}
	
	
	
	/**
	 * 通过类结构反射获取数据数据库查询Map数据<br/> 
	 * prefix 前缀
	 * ClassName:实体java类的类名<br/>
	 * classField:实体java类的字段名<br/>
	 * tableColum:数据库的字段名<br/>
	 * {<br/>
	 * 		"[classField]"：value,					//多个键值对<br/>
	 * 		"[classField]Not":"not",				//该字段查询条件取反<br/>
	 * 		"desc"/"asc":[tableColum],			//降序/升序的条件<br/>
	 * 		"definex":sql,						//自定义查询条件<br/>
	 * 		"[ClassName]":{						//连接查询的类名<br/>
	 * 			....							//其值为Map，结构同上一级<br/>
	 * 			"on":[tableColum]					//可不指定，但如果原对象有两个字段绑定到当前对象，指定当前表关联到原对象哪个字段,
	 * 		}<br/>
	 * }<br/>
	 */
	public static Map getQueryFormParams(Class modelClass){
		return getQueryFormParams(modelClass,"");
	}
	@SuppressWarnings("unchecked")
	public static Map getQueryFormParams(Class modelClass,String prefix){
		IbatisMap objects=new IbatisMap();
		try {
			objects =(IbatisMap) modelClass.getMethod("where").invoke(null);
		} catch (Exception e) {
			e.printStackTrace();					
		}
		{
			//把request传过来的(String)参数转换成java对象			
			Field[] fields = Class(modelClass,"F").getFields();
			for(Field field:fields){
				type type = field.getAnnotation(type.class);
				like like = field.getAnnotation(like.class);
				if(type==null)continue;
				try {
					Object value = Utils.getObject(prefix+field.getName(),type.value());
					if(value!=null)
						objects.put(field.getName(),value);
					if(type.value()==String.class && Utils.empty((String)value)){
						objects.remove(field.getName());
					}else if(!Utils.empty(prefix) && like!=null){
						String sValue = (String) value;
						if(!Utils.empty(sValue))
							objects.put(field.getName(),"%"+sValue+"%");
					}
					if(objects.get(field.getName())==null){
						String strIn=Utils.getString(prefix+field.getName());
						if(!Utils.empty(strIn) && strIn.startsWith("[") && strIn.endsWith("]") && strIn.indexOf(",")>-1){
							objects.put(field.getName(),strIn);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				try {
					String strYesNot = Utils.getString(prefix+field.getName()+"YesNot");
					if(Utils.equals("not", strYesNot)){
						objects.put(prefix+field.getName()+"Not", "not");
					}else if(Utils.equals("yes", strYesNot)){
						objects.put(prefix+field.getName()+"Not", "");
					}
					if(!Utils.empty(strYesNot))
						objects.put(prefix+field.getName()+"YesNot", strYesNot);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			//获取日期表达式值
			for(Field field:fields){
				type type = field.getAnnotation(type.class);
				if(type==null || type.value()!=Date.class)continue;
				if(field.getName().endsWith("Start")||field.getName().endsWith("End"))continue;
				String value = Utils.getString(prefix+field.getName()+"Exp");
				if(Utils.empty(value))continue;
				DateExp dateExp = Utils.DateExp(value.toString());
				objects.put(field.getName()+"Start",dateExp.start);
				objects.put(field.getName()+"End",dateExp.end);
			}
		}
		
		if(Utils.empty(prefix)){
			//取连接查询的对象名称
			Field[] fields = modelClass.getDeclaredFields();
			for(Field field:fields){
				relate relate = field.getAnnotation(relate.class);
				column column = field.getAnnotation(column.class);
				on on = field.getAnnotation(on.class);
				if(relate==null || (column==null && on==null))continue;//如果未关联对象	
				if(Utils.getBoolean(field.getName()+"$on",false)==true){
					Field mappingField = null;
					try{
						mappingField = modelClass.getDeclaredField(relate.value());//否则根据关联对象取该类映射字段
					}catch(Exception ex){}
					if(mappingField==null)continue;
					Class<?> relatClass = mappingField.getType();			
					Map relateObject = getQueryFormParams(relatClass,field.getName()+"$");
					if(relateObject.isEmpty())continue;
					relateObject.put("on", on==null?column.value():on.value());
					if(relateObject!=null){
						//放入当前子Map
						objects.put(Utils.ForMat(field.getName()),relateObject);
					}
				}
			}
		}
		
		
		Field[] fields = modelClass.getDeclaredFields();
		for(Field field:fields){
			relate relate = field.getAnnotation(relate.class);
			column column = field.getAnnotation(column.class);
			on on = field.getAnnotation(on.class);
			if(relate==null || (column==null && on==null))continue;//如果未关联对象	
			//如果on字段有值，转存到子条件
			if(on!=null){
				try {
					Object value = Utils.getObject(prefix+field.getName(),Long.class);
					if(value!=null){
						Field mappingField = modelClass.getDeclaredField(relate.value());//否则根据关联对象取该类映射字段
						if(mappingField!=null){
							Class<?> relatClass = mappingField.getType();	
							IbatisMap where$on=(IbatisMap) relatClass.getMethod("where").invoke(null);
							for(Field f:relatClass.getDeclaredFields()){//当前字段值转存到子对象主键字段
								if(f.getAnnotation(primary.class)!=null){
									where$on.put(f.getName(), value);
									break;
								}
							}
							where$on.put("on",on.value());
							objects.put(Utils.ForMat(field.getName()),where$on);
						}
					}					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return objects;
	}
	
	/**
	 * 重置请求参数,主要是把百分号去掉一下
	 * @param params
	 */
	public static void resetQueryFormParams(Map params){
		for(Object key:params.keySet()){
			Object value = params.get(key);
			if(value==null)continue;
			if(value instanceof String){
				params.put(key, ((String)value).replace("%", ""));
			}else if(value instanceof Map){
				resetQueryFormParams((Map) value);
			}
		}
	}
	
	/**
	 * 获取内部类
	 * @param modelClass
	 * @param internalClassName
	 * @return
	 */
	private static Class Class(Class modelClass,String internalClassName){
		Class[] classes = modelClass.getDeclaredClasses();
		for(Class cls:classes)
			if(cls.getSimpleName().equals(internalClassName))
				return cls;
		return null;
	}
	
	
	
}